<template>
  <div class="login-container">
    <h1>用户登录</h1>
    <form @submit.prevent="handleSubmit">
      <div class="form-group">
        <label for="username">用户名：</label>
        <input 
          type="text" 
          id="username" 
          v-model="formData.username" 
          :class="{ 'error-input': errors.username }"
          placeholder="请输入用户名"
        >
        <span v-if="errors.username" class="error">{{ errors.username }}</span>
      </div>

      <div class="form-group">
        <label for="password">密码：</label>
        <input 
          type="password" 
          id="password" 
          v-model="formData.password"
          :class="{ 'error-input': errors.password }"
          placeholder="请输入密码"
        >
        <span v-if="errors.password" class="error">{{ errors.password }}</span>
      </div>

      <div class="form-group">
        <button type="submit" :disabled="loading">
          {{ loading ? '登录中...' : '登录' }}
        </button>
      </div>
    </form>

    <div v-if="loginMessage" class="message" :class="loginStatus">
      {{ loginMessage }}
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 表单数据
const formData = reactive({
  username: '',
  password: ''
})

// 错误信息
const errors = reactive({
  username: '',
  password: ''
})

// 登录状态
const loading = ref(false)
const loginMessage = ref('')
const loginStatus = ref('')

// 表单验证
const validateForm = () => {
  let isValid = true
  
  // 重置错误信息
  errors.username = ''
  errors.password = ''

  // 用户名验证 (4-20位字母数字)
  if (!formData.username) {
    errors.username = '用户名不能为空'
    isValid = false
  } else if (!/^[a-zA-Z0-9]{4,20}$/.test(formData.username)) {
    errors.username = '用户名必须是4-20位字母或数字'
    isValid = false
  }

  // 密码验证 (6-16位)
  if (!formData.password) {
    errors.password = '密码不能为空'
    isValid = false
  } else if (formData.password.length < 6 || formData.password.length > 16) {
    errors.password = '密码长度需为6-16位'
    isValid = false
  }

  return isValid
}

// 模拟登录API
const mockLoginApi = (credentials) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      // 模拟成功登录
      if (credentials.username === 'admin' && credentials.password === '123456') {
        resolve({ 
          success: true, 
          user: { 
            id: 1, 
            name: '管理员',
            token: 'fake-jwt-token'
          }
        })
      } else {
        reject({ 
          success: false, 
          message: '用户名或密码错误' 
        })
      }
    }, 1500) // 模拟网络延迟
  })
}

// 处理登录提交
const handleSubmit = async () => {
  // 验证表单
  if (!validateForm()) return
  
  loading.value = true
  loginMessage.value = ''
  
  try {
    // 调用登录API
    const response = await mockLoginApi({
      username: formData.username,
      password: formData.password
    })
    
    if (response.success) {
      loginMessage.value = '登录成功！正在跳转...'
      loginStatus.value = 'success'
      
      // 保存用户信息到本地存储
      localStorage.setItem('user', JSON.stringify(response.user))
      
      // 跳转到首页
      setTimeout(() => {
        router.push({ name: 'Home' })
      }, 1000)
    }
  } catch (error) {
    // 处理登录失败
    loginMessage.value = error.message || '登录失败，请重试'
    loginStatus.value = 'error'
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-container {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.form-group {
  margin-bottom: 20px;
  text-align: left;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 16px;
  box-sizing: border-box;
}

input.error-input {
  border-color: #ff4d4f;
}

button {
  width: 100%;
  padding: 12px;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #2980b9;
}

button:disabled {
  background-color: #a0c7e4;
  cursor: not-allowed;
}

.error {
  color: #ff4d4f;
  font-size: 14px;
  display: block;
  margin-top: 5px;
}

.message {
  padding: 10px;
  border-radius: 4px;
  text-align: center;
  margin-top: 20px;
}

.message.success {
  background-color: #d4edda;
  color: #155724;
}

.message.error {
  background-color: #f8d7da;
  color: #721c24;
}
</style>